import {
  Button,
  DatePicker,
  Dropdown,
  Form,
  Input,
  message,
  Space,
  Typography,
  Divider,
} from "antd";
import React from "react";
import FileSaver from "file-saver";
import axios from "axios";
import { InboxOutlined } from "@ant-design/icons";
import Dragger from "antd/es/upload/Dragger";
import xlsx from "node-xlsx";
import {
  DOWNLOAD_TEMPLATE,
  PRODUCT_UPLOAD_FILES,
} from "../../../../constants/api-constants";

const { Title } = Typography;
const col = { width: 50, type: "n", color: "rgb(17,17,17)" };
const cols: { width: number; type: string }[] = [];

const tmpArray = [
  "name",
  "unit",
  "model",
  "organization",
  "address",
  "patent",
  "registrationStatus",
  "application_area",
  "contactPerson",
  "contactEmail",
  "contactTel",
  "description",
];
for (let i = 1; i <= tmpArray.length; i++) {
  cols.push(col);
}
interface configProps {
  setDate: Function;
  setApplication: Function;
  setPage: Function;
  setKeyword: Function;
  setName: Function;
  setDetailShow: Function;
  setRecord: Function;
  getList: Function;
  mainData: any;
}
export default (props: configProps) => {
  const {
    setName,
    setKeyword,
    setPage,
    setApplication,
    setDate,
    setDetailShow,
    setRecord,
    mainData,
    getList,
  } = props;
  // 先使用any等后续解决
  const propsw: any = {
    name: "file",
    action: PRODUCT_UPLOAD_FILES,
    headers: { Authorization: localStorage.getItem("Authorization") },
    data: { username: localStorage.getItem("userName") },
    beforeUpload(file: File) {
      return new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsArrayBuffer(file);
        reader.onload = () => {
          if (reader.result && typeof reader.result !== "string") {
            const buf = reader.result;
            const parse = xlsx.parse(buf, { type: "buffer" });
            const { data } = parse[0];
            let dataFilter: any = data.filter((v: any[], i: number) => {
              if (i !== 0) {
                return !(v[6] !== "已注册" && v[6] !== "未注册");
              } else {
                return true;
              }
            });
            if (dataFilter && dataFilter.length === 1) {
              message.error("文件上传失败,请下载模板文件查看错误", 5);
              return;
            }

            if (JSON.stringify(data[0]) !== JSON.stringify(tmpArray)) {
              message.error(
                "上传文件中首行不正确请重试(请下载模板文件查看)",
                6
              );
            } else {
              /*else if (dataFilter.length !== data.length) {
              dataFilter.forEach((_v: any, i: string | number) => {
                if (i !== 0) {
                  dataFilter[i][8] = new Date(
                    (dataFilter[i][8] - 25569) * 24 * 60 * 60 * 1000
                  );
                }
              });
              const blob = new Blob(
                [
                  xlsx.build([{ name: "template", data: dataFilter }], {
                    "!cols": cols,
                  }),
                ],
                {
                  type: "application/octet-stream",
                }
              );
              message.info(
                "已将筛选出正确数据并上传(已自动下载筛选后的文件)",
                9
              );
              resolve(blob);
              FileSaver.saveAs(blob, "默认正确值.xlsx");
            } */
              const blob = new Blob(
                [
                  xlsx.build([{ name: "template", data: dataFilter }], {
                    "!cols": cols,
                  }),
                ],
                {
                  type: "application/octet-stream",
                }
              );
              message.success("文件检查通过,请等待后端验证并返回结果", 6);
              resolve(blob);
            }
          } else {
            message.error("文件读取失败请检查格式");
          }
        };
      });
    },
    onChange(info: {
      file: {
        response: { msg: string; mainData: any };
        status: string;
        name: any;
      };
      fileList: any;
    }) {
      if (info.file.status === "done") {
        setPage(1);
        getList();
        message.success(`${info.file.name} 上传成功.`);
      } else if (info.file.status === "error") {
        setPage(1);
        getList();
        const data = info.file.response.mainData.data;
        if (!data) {
          return;
        }
        const blob = new Blob(
          [
            xlsx.build([{ name: "template", data }], {
              "!cols": cols,
            }),
          ],
          {
            type: "application/octet-stream",
          }
        );
        FileSaver.saveAs(blob, "error.xlsx");

        message.error(`${info.file.response.msg}`, 15);
      }
    },
  };

  const menu = (
    <div
      style={{
        background: "rgb(251,251,251)",
        padding: "12px",
        boxShadow:
          "0 8px 8px rgba(96,185,234,.24),0 0 8px rgba(96,185,234,.12)",
        borderRadius: "0.4rem",
      }}
    >
      <Button
        onClick={() => {
          axios
            .post(DOWNLOAD_TEMPLATE, {
              filename: "template.xlsx",
              dir: "product",
            })
            .then((r) => {
              const { file, filename } = r.data.mainData;

              let blob = new Blob(
                [
                  xlsx.build(file, {
                    "!cols": cols,
                  }),
                ],
                {
                  type: "application/octet-stream",
                }
              );
              FileSaver.saveAs(blob, filename);
            })
            .catch(() => {});
        }}
        style={{
          overflow: "hidden",
          whiteSpace: "normal",
          wordBreak: "break-all",
          fontSize: "0.9rem",
          padding: "0",
          width: "10vw",
          height: "auto",
          marginBottom: "2vh",
        }}
      >
        下载导入模板
      </Button>
      <Dragger accept={".xlsx"} {...propsw} style={{ padding: "0 1vw" }}>
        <p className="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        <p className="ant-upload-text">请拖拽.XLSX文件至此或使用点击上传</p>
        <p className="ant-upload-hint">
          支持单次或批量上传。 严禁上传公司资料或其他公司文件
        </p>
      </Dragger>
    </div>
  );
  return (
    <>
      <div>
        <Title level={4}>筛选查询</Title>
      </div>

      <Form layout="inline">
        <Form.Item name="name">
          <Input
            onChange={(e) => {
              setPage(1);
              setName(e.target.value ?? "");
            }}
            placeholder={"请输入成果名称"}
          />
        </Form.Item>
        <Form.Item name="keyword">
          <Input
            onChange={(e) => {
              console.log(e.target.value);
              setPage(1);
              setKeyword(e.target.value ?? "");
            }}
            placeholder={"请输入所属单位"}
          />
        </Form.Item>
        <Form.Item name="application">
          <Input
            onChange={(e) => {
              setPage(1);
              setApplication(e.target.value ?? "");
            }}
            placeholder={"请输入应用领域"}
          />
        </Form.Item>
        <Form.Item name="date">
          <DatePicker
            onChange={(e) => {
              setPage(1);

              console.log(e);
              if (e) {
                const date = e.toDate();

                setDate(
                  `${date.getFullYear()}-${
                    date.getUTCMonth() + 1 > 10
                      ? date.getUTCMonth() + 1
                      : "0" + (date.getUTCMonth() + 1)
                  }-${
                    date.getUTCDate() > 10
                      ? date.getUTCDate()
                      : "0" + date.getUTCDate()
                  }`
                );
              } else {
                setDate("");
              }
            }}
          />
        </Form.Item>
      </Form>

      <Divider orientation="left" />
      <h2 style={{ fontWeight: "bold", display: "inline-block" }}>详细信息</h2>
      {window.localStorage.getItem("identity") === null ? null : (
        <Space style={{ float: "right" }}>
          <Dropdown
            trigger={["click"]}
            placement="bottomRight"
            arrow
            overlay={menu}
          >
            <Button type="primary">批量导入</Button>
          </Dropdown>
          <Button
            type="primary"
            onClick={() => {
              if (mainData) {
                setDetailShow();
                const { patents } = mainData;
                const application_areas = mainData.application_area;
                const organizationw = mainData.organizations;
                setRecord({
                  patents,
                  organizationw,
                  application_areas,
                });
              }
            }}
          >
            添加成果信息
          </Button>
        </Space>
      )}
    </>
  );
};
